package cn.edu.scau.common.utils;

import org.apache.commons.lang3.time.DateUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @description: 时间工具
 * @author: yuxiang
 * @create: 2021-03-31 15:34
 **/
public class TimeUtils {


    /**
     * 获取自定义时间日期
     *
     * @param date
     * @param pattern 日期格式 比如 "yyyy-MM-dd HH:mm:ss" "yyyy-MM-dd"
     * @return
     * @throws ParseException
     */
    public static Date getDIYDate(String date, String pattern) {
        DateFormat dateFormat2 = new SimpleDateFormat(pattern);
        Date myDate2 = null;
        try {
            myDate2 = dateFormat2.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return myDate2;
    }

    public static Boolean isDatePattern(String s) {
        String[] patterns = {"yyyy-MM-dd",
                "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
                "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd"};
        if (s == null) {
            return false;
        }
        try {
            Date d = DateUtils.parseDate(s, patterns);
            if (d != null) {
                return true;
            }
        } catch (ParseException e) {
            return false;
        }
        return false;
    }


    /**
     * 获取时间
     * @param s 日期字符串
     * @return
     */
    public static Date getDateByString(String s){
        DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate2 = null;
        try {
            myDate2 = dateFormat2.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return myDate2;
    }
    public static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    public static Date asDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDate asLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static LocalDateTime asLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
